package com.phiture.erp.produce.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingPageReqVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingSaveReqVO;
import com.phiture.erp.produce.core.service.ErpProduceRoutingService;
import com.phiture.erp.produce.dal.entity.ErpProduceProcessDO;
import com.phiture.erp.produce.dal.entity.ErpProduceRoutingDO;
import com.phiture.erp.produce.dal.entity.ErpProduceRoutingDetailDO;
import com.phiture.erp.produce.dal.mapper.ErpProduceProcessMapper;
import com.phiture.erp.produce.dal.mapper.ErpProduceRoutingDetailMapper;
import com.phiture.erp.produce.dal.mapper.ErpProduceRoutingMapper;
import com.phiture.erp.produce.dal.pojo.dto.ErpProduceRoutingDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.phiture.erp.common.constants.ErrorCodeConstants.PRODUCE_ROUTING_NOT_EXISTS;

/**
 * 工艺路线 Service 实现类
 *
 * @author lekaihuai
 */
@Service
@Validated
public class ErpProduceRoutingServiceImpl implements ErpProduceRoutingService {

    @Resource
    private ErpProduceRoutingMapper produceRoutingMapper;

    @Resource
    private ErpProduceProcessMapper produceProcessMapper;
    @Resource
    private ErpProduceRoutingDetailMapper produceRoutingDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProduceRouting(ErpProduceRoutingSaveReqVO createReqVO) {
        // 插入
        ErpProduceRoutingDO produceRouting = BeanUtils.toBean(createReqVO, ErpProduceRoutingDO.class);
        produceRoutingMapper.insert(produceRouting);

        // 插入子表
        createProduceRoutingDetailList(produceRouting.getId(), createReqVO.getProduceRoutingDetails());
        // 返回
        return produceRouting.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduceRouting(ErpProduceRoutingSaveReqVO updateReqVO) {
        // 校验存在
        validateProduceRoutingExists(updateReqVO.getId());
        // 更新
        ErpProduceRoutingDO updateObj = BeanUtils.toBean(updateReqVO, ErpProduceRoutingDO.class);
        produceRoutingMapper.updateById(updateObj);

        // 更新子表
        updateProduceRoutingDetailList(updateReqVO.getId(), updateReqVO.getProduceRoutingDetails());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduceRouting(Long id) {
        // 校验存在
        validateProduceRoutingExists(id);
        // 删除
        produceRoutingMapper.deleteById(id);

        // 删除子表
        deleteProduceRoutingDetailByRoutingId(id);
    }

    private void validateProduceRoutingExists(Long id) {
        if (produceRoutingMapper.selectById(id) == null) {
            throw exception(PRODUCE_ROUTING_NOT_EXISTS);
        }
    }

    @Override
    public ErpProduceRoutingDO getProduceRouting(Long id) {
        return produceRoutingMapper.selectById(id);
    }

    @Override
    public PageResult<ErpProduceRoutingDO> getProduceRoutingPage(ErpProduceRoutingPageReqVO reqVO) {

        Page<ErpProduceRoutingDO> page = new Page<>(reqVO.getPageNo(), reqVO.getPageSize());
        ErpProduceRoutingDTO dto = new ErpProduceRoutingDTO();
        BeanUtils.copyProperties(reqVO, dto);
        IPage<ErpProduceRoutingDO> result = produceRoutingMapper.selectProduceRoutingList(page, dto, TenantContextHolder.getTenantId()); // 这里不需要传入条件，如果需要可以在方法中添加参数。
        PageResult<ErpProduceRoutingDO> pageResult = new PageResult<>(page.getRecords(), page.getTotal());

        return pageResult;
    }

    @Override
    public Map<Long, String> getProduceRoutingMap(Long materialId) {
        List<ErpProduceRoutingDO> list = produceRoutingMapper.selectList(ErpProduceRoutingDO::getMaterialId, materialId);
        return CollUtil.isEmpty(list) ? Collections.emptyMap() : list.stream().collect(Collectors.toMap(ErpProduceRoutingDO::getId, ErpProduceRoutingDO::getRoutingName));
    }

    @Override
    public Map<Long, Long> getProduceRoutingMap(Collection<Long> materialIds) {
        List<ErpProduceRoutingDO> list = produceRoutingMapper.selectList(ErpProduceRoutingDO::getMaterialId, materialIds);
        return CollUtil.isEmpty(list)
                ? Collections.emptyMap()
                : list.stream().collect(Collectors.toMap(ErpProduceRoutingDO::getMaterialId, ErpProduceRoutingDO::getId));
    }

    // ==================== 子表（工艺路线明细） ====================

    @Override
    public List<ErpProduceRoutingDetailDO> getProduceRoutingDetailListByRoutingId(Long routingId) {
        return produceRoutingDetailMapper.selectListByRoutingId(routingId);
    }

    @Override
    public List<ErpProduceProcessDO> getProduceRoutingDetailListByMaterialId(Long materialId) {
        List<ErpProduceProcessDO> result = produceRoutingDetailMapper.selectListByMaterialId(materialId);
        // 如果没有数据，取出工序表中所有status为1的工序数据
        if (result.isEmpty()) {
            result = produceProcessMapper.selectList(new MPJLambdaWrapperX<ErpProduceProcessDO>()
                    .eq(ErpProduceProcessDO::getStatus, 1));
        }
        return result;
    }

    private void createProduceRoutingDetailList(Long routingId, List<ErpProduceRoutingDetailDO> list) {
        list.forEach(o -> o.setRoutingId(routingId));
        produceRoutingDetailMapper.insertBatch(list);
    }

    private void updateProduceRoutingDetailList(Long routingId, List<ErpProduceRoutingDetailDO> list) {
        deleteProduceRoutingDetailByRoutingId(routingId);
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createProduceRoutingDetailList(routingId, list);
    }

    private void deleteProduceRoutingDetailByRoutingId(Long routingId) {
        produceRoutingDetailMapper.deleteByRoutingId(routingId);
    }

}